/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */
#include <sstream>
#include "../../common/data_utils.h"
#include "kernel_tiling/kernel_tiling.h"
#include "tiling/platform/platform_ascendc.h"
#include "op_host/matmul_ibshare_custom_tiling.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"

extern void matmul_ibshare_custom_do(uint32_t coreDim, void* stream,
                             uint8_t* a, uint8_t* b, uint8_t* c,
                             uint8_t* workspace, uint8_t* tiling);
#else
#include "tikicpulib.h"
extern "C" void matmul_ibshare_custom(uint8_t* a, uint8_t* b, uint8_t* c,
                              uint8_t* workspace, uint8_t* tiling);
#endif


namespace {
constexpr bool hasBias = false;
constexpr bool ibshareA = true;
constexpr bool ibshareB = true;

struct MatrixFileSize
{
    size_t x1FileSize;
    size_t x2FileSize;
    size_t yFileSize;
    size_t biasFileSize;
};
}

namespace MatmulHost {
static size_t GetSysWorkSpaceSize()
{
    auto ascendcPlatform = platform_ascendc::PlatformAscendCManager::GetInstance();
    return static_cast<size_t>(ascendcPlatform->GetLibApiWorkSpaceSize());
}

// CPU debug mode
#ifdef ASCENDC_CPU_DEBUG
void TestMatmulCpu(int64_t m, int64_t n, int64_t k, const MatrixFileSize& matrixFileSize)
{
    size_t aFileSize = matrixFileSize.x1FileSize;  // uint16_t represent half
    size_t bFileSize = matrixFileSize.x2FileSize;  // uint16_t represent half
    size_t cFileSize = matrixFileSize.yFileSize;
    size_t workspaceSize = GetSysWorkSpaceSize();
    size_t tilingFileSize = sizeof(TCubeTiling);
    uint32_t mixRatio = 2;  // AIC:AIV = 1:2
    MatmulHost::MatmulCaseParams testCaseParams{
        static_cast<int32_t>(m), static_cast<int32_t>(n), static_cast<int32_t>(k), hasBias, ibshareA, ibshareB};

    uint8_t* a = (uint8_t* )AscendC::GmAlloc(aFileSize);
    uint8_t* b = (uint8_t* )AscendC::GmAlloc(bFileSize);
    uint8_t* c = (uint8_t* )AscendC::GmAlloc(cFileSize);
    uint8_t* workspace = (uint8_t* )AscendC::GmAlloc(workspaceSize);
    uint8_t* tiling = (uint8_t* )AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/x1_gm.bin", aFileSize, a, aFileSize);
    ReadFile("../input/x2_gm.bin", bFileSize, b, bFileSize);
    const auto& tilingData = MatmulHost::GenerateTiling(testCaseParams);
    memcpy_s(tiling, tilingFileSize, &tilingData, tilingFileSize);

    uint32_t blockDim;
    if (ibshareA && ibshareB) {
        blockDim = tilingData.usedCoreNum;
    } else {
        blockDim = tilingData.usedCoreNum / mixRatio;
    }

    ICPU_RUN_KF(matmul_ibshare_custom, blockDim, a, b, c, workspace, tiling);

    WriteFile("../output/output.bin", c, cFileSize);

    AscendC::GmFree((void *)a);
    AscendC::GmFree((void *)b);
    AscendC::GmFree((void *)c);
    AscendC::GmFree((void *)workspace);
    AscendC::GmFree((void *)tiling);
}
// NPU
#else
void MatmulOp(uint8_t* a, uint8_t* b, uint8_t* c, int64_t m, int64_t n, int64_t k,
    void* stream = nullptr)
{
    // Init args
    uint8_t* workspaceDevice = nullptr;

    // Query workspace size
    size_t workspaceSize = GetSysWorkSpaceSize();

    // Allocate workspace on device
    CHECK_ACL(aclrtMalloc((void**)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));

    // Initialize kernel with arguments and workspace pointer
    uint8_t* tilingHost = nullptr;
    uint8_t* tilingDevice = nullptr;
    size_t tilingFileSize = sizeof(TCubeTiling);

    MatmulHost::MatmulCaseParams testCaseParams{
            static_cast<int32_t>(m), static_cast<int32_t>(n), static_cast<int32_t>(k), hasBias, ibshareA, ibshareB};

    // Calculate Tiling
    uint32_t mixRatio = 2;  // AIC:AIV = 1:2
    const auto tilingData = MatmulHost::GenerateTiling(testCaseParams);
    uint32_t blockDim;
    if (ibshareA && ibshareB) {
        blockDim = tilingData.usedCoreNum;
    } else {
        blockDim = tilingData.usedCoreNum / mixRatio;
    }

    CHECK_ACL(aclrtMallocHost((void**)(&tilingHost), tilingFileSize));
    CHECK_ACL(aclrtMalloc((void**)&tilingDevice, tilingFileSize,
                          ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMemcpy(tilingHost, tilingFileSize, &tilingData,
                          tilingFileSize, ACL_MEMCPY_HOST_TO_HOST));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, tilingHost,
                          tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));
    // Launch kernel
    matmul_ibshare_custom_do(blockDim, stream, a, b, c, workspaceDevice, tilingDevice);
    CHECK_ACL(aclrtFreeHost(tilingHost));
    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFree(tilingDevice));
}

void TestAclInit(aclrtContext& context, aclrtStream& stream, int64_t& deviceId)
{
    CHECK_ACL(aclInit(nullptr));
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    CHECK_ACL(aclrtCreateStream(&stream));
}

void TestAclDeInit(aclrtContext& context, aclrtStream& stream, int64_t& deviceId)
{
    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
}

void TestMatmul(int64_t m, int64_t n, int64_t k, const MatrixFileSize& matrixFileSize)
{
    size_t aFileSize = matrixFileSize.x1FileSize;  // uint16_t represent half
    size_t bFileSize = matrixFileSize.x2FileSize;  // uint16_t represent half
    size_t cFileSize = matrixFileSize.yFileSize;

    aclrtContext context;
    aclrtStream stream = nullptr;
    int64_t deviceId = 0;
    TestAclInit(context, stream, deviceId);

    uint8_t* aHost;
    uint8_t* aDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&aHost), aFileSize));
    CHECK_ACL(aclrtMalloc((void **)&aDevice, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/x1_gm.bin", aFileSize, aHost, aFileSize);
    CHECK_ACL(aclrtMemcpy(aDevice, aFileSize, aHost, aFileSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* bHost;
    uint8_t* bDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&bHost), bFileSize));
    CHECK_ACL(aclrtMalloc((void **)&bDevice, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/x2_gm.bin", bFileSize, bHost, bFileSize);
    CHECK_ACL(aclrtMemcpy(bDevice, bFileSize, bHost, bFileSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* cHost;
    uint8_t* cDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&cHost), cFileSize));
    CHECK_ACL(aclrtMalloc((void **)&cDevice, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    MatmulOp(aDevice, bDevice, cDevice, m, n, k, stream);
    CHECK_ACL(aclrtSynchronizeStream(stream));

    CHECK_ACL(aclrtMemcpy(cHost, cFileSize, cDevice, cFileSize,
                          ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output.bin", cHost, cFileSize);

    CHECK_ACL(aclrtFree(aDevice));
    CHECK_ACL(aclrtFreeHost(aHost));
    CHECK_ACL(aclrtFree(bDevice));
    CHECK_ACL(aclrtFreeHost(bHost));
    CHECK_ACL(aclrtFree(cDevice));
    CHECK_ACL(aclrtFreeHost(cHost));

    TestAclDeInit(context, stream, deviceId);
}
#endif
}


int32_t main(int32_t argc, const char *args[])
{
    int64_t inputParams[3] = {1, 1, 1};
    for (int32_t i = 1; i < argc && i < 4; ++i) { // 4
        std::stringstream ss(args[i]);
        ss >> inputParams[i - 1];
    }
    auto ascendcPlatform = platform_ascendc::PlatformAscendCManager::GetInstance(SOC_VERSION);
    int64_t M = inputParams[0];
    int64_t N = inputParams[1];
    int64_t K = inputParams[2];
    MatrixFileSize matrixFileSize;
    // uint16_t represent half
    matrixFileSize.x1FileSize = static_cast<size_t>(M * K) * sizeof(uint16_t);
    matrixFileSize.x2FileSize = static_cast<size_t>(K * N) * sizeof(uint16_t);
    matrixFileSize.yFileSize = static_cast<size_t>(M * N) * sizeof(float);
    matrixFileSize.biasFileSize = static_cast<size_t>(1 * N) * sizeof(float);
#ifdef ASCENDC_CPU_DEBUG
    MatmulHost::TestMatmulCpu(M, N, K, matrixFileSize);
#else
    MatmulHost::TestMatmul(M, N, K, matrixFileSize);
#endif
    return 0;
}
